<%-- 
    Document   : decorator-chat
    Created on : 9 черв 2012, 23:45:32
    Author     : Volodymyr Lavrynovych <volodya.lavrynovych@gmail.com>
--%>

<%@page import="mycompany.helper.ApplicationContentHelper"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>

<% ApplicationContentHelper helper = new ApplicationContentHelper(request);%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <%=helper.getCss(helper.BOOTSTRAP_CSS)%>
        <style type="text/css">
            body {
                padding-top: 60px;
                padding-bottom: 0px;
            }
            .sidebar-nav {
                padding: 9px 0;
            }
            .message {
                padding: 5px;
                width: 350px;
                word-break: break-all;
            }
        </style>
        <%=helper.getCss(helper.BOOTSTRAP_RESPONSIVE_CSS)%>
        <%=helper.getJQuery()%>
        <%=helper.getNotifier()%>
        
        <script type="text/javascript">
            var lastMessageId = -1;
            var timeout = 1500;
            var $container;
            var $input;
            var $chatinfo;
            var isActive = true;
            var hasPartner = false;
            
            //TODO: refactor insertAtCaret method
            function insertAtCaret(area,text) {
                var txtarea = area[0];
                var scrollPos = txtarea.scrollTop;
                var strPos = 0;
                var br = ((txtarea.selectionStart || txtarea.selectionStart == '0') ? 
                    "ff" : (document.selection ? "ie" : false ) );
                if (br == "ie") { 
                    txtarea.focus();
                    var range = document.selection.createRange();
                    range.moveStart ('character', -txtarea.value.length);
                    strPos = range.text.length;
                }
                else if (br == "ff") strPos = txtarea.selectionStart;

                var front = (txtarea.value).substring(0,strPos);  
                var back = (txtarea.value).substring(strPos,txtarea.value.length); 
                txtarea.value=front+text+back;
                strPos = strPos + text.length;
                if (br == "ie") { 
                    txtarea.focus();
                    var range = document.selection.createRange();
                    range.moveStart ('character', -txtarea.value.length);
                    range.moveStart ('character', strPos);
                    range.moveEnd ('character', 0);
                    range.select();
                }
                else if (br == "ff") {
                    txtarea.selectionStart = strPos;
                    txtarea.selectionEnd = strPos;
                    txtarea.focus();
                }
                txtarea.scrollTop = scrollPos;
            }
            
            $(document).ready(function() {
                $('#passwordDialog').hide();
                $container = $('#messageContainer');
                $input = $('#text');
                $input.focus();
                $chatinfo = $('#chatinfo');
                periodicalUpdate();
            }).keydown(function(e){
                e = e || window.event;
                if(e.ctrlKey && e.keyCode == 13) { //ctrl + enter
                    insertAtCaret($input,"\n");
                    $input.focus();
                } else if(e.keyCode == 13) { //enter
                    send();
                } else if(e.keyCode == 27) { //esc
                    exit();
                }
            });
            
            function periodicalUpdate(){
                refresh();
                window.setTimeout(periodicalUpdate, timeout);
            }
            
            function exit(){
                $.ajax({
                    url: "leave",
                    type: "POST",
                    success: function(result) {
                    }
                });
                window.close();
            }
            
            function updateStatus(){
                $.ajax({
                    url: "status",
                    success: function(result) {
                        isActive = result=='true';
                        var color = isActive ? 'greenyellow' : 'red';
                        var status = isActive ? 'Active' : 'Closed';
                        $('#chatStatus').html('<span style="color: '+color+'">'+status+'</span>');
                    }
                });
            }
            
            function allowChat(isAllow){
                if(isAllow){
                    $('#sendButton').removeClass("disabled");
                    $input.attr("disabled", false);
                    $input.focus();
                } else {
                    $('#sendButton').addClass("disabled");
                    $input.attr("disabled", true);
                }
            }
            
            function send(){
                if($('#sendButton').hasClass("disabled")) return; // send button is disabled
                
                var message = $.trim($input.val());
                if(message.length==0) return; //message is empty
                $.ajax({
                    url: "addMessage",
                    type: "POST",
                    data: {
                        text: encodeURIComponent(message)
                    },
                    success: function(result) {
                        if(result=='true'){
                            $input.val("");
                            getNewMessages();
                        }
                    }
                });
                $input.focus();
            }
            
            function getPartner(){
                $.ajax({
                    url: "partner",
                    type: "POST",
                    success: function(partner) {
                        hasPartner = partner!="";
                        var result = partner!="" ? "with <b>Anonymous</b>" : "You are alone";
                        $('#partner').html(result);
                    }
                });
            }
            
            function getRemovedMessages(){
                $.ajax({
                    url: "getRemovedMessages",
                    type: "POST",
                    success: function(ids) {
                        if(ids.length>0){
                            $.each(ids, function(index, id){
                                markAsRemoved(id);
                            });
                        } else {
                            //skip
                        }
                    }
                });
            }
            
            function getNewMessages(){
                $.ajax({
                    url: "getMessages",
                    type: "POST",
                    data: {
                        lastMessageId: lastMessageId
                    },
                    success: function(messages) {
                        if(messages.length>0){
                            $.each(messages, function(index, message){
                                addMessage(message);
                            });
                        } else {
                            //skip
                        }
                    }
                });
            }
            
            function select(obj){
                $(obj).css({"background-color": "#fafafa"});
                $(obj).find('.icon-trash').show();
            }
            
            function unselect(obj){
                $(obj).css({"background-color": "#ffffff"});
                $(obj).find('.icon-trash').hide();
            }
            
            function addMessage(message){
                var row = $('<div id="'+message.id+'" class="message" ondblclick="addQuote(this)" onmouseover="select(this)" user="'+message.userId+'" onmouseout="unselect(this)">');
                
                var isMyMessage = message.userId=='${userId}';
                
                var date = new Date(message.date);
                var info = $('<div style="color: #999">').text(formatDate(date)+" - ").append($('<b style="color: #666">').text(isMyMessage ? 'Me' : 'Anonymous'));
                var text = $('<div class="text">').text(decodeURIComponent(message.text));
                
                if(isMyMessage){
                    var remove = $('<a onclick="removeMessage('+message.id+')" class="icon-trash close"></a>').hide();
                    row.append(remove); 
                }
                
                row.append(info).append(text);
                $container.append(row);
                lastMessageId = message.id;
                $container.find('#'+message.id)[0].scrollIntoView(false);
            }
            
            function markAsRemoved(id){
                var message = $container.find('#'+id);
                message.find('.text').html('<i style="color: #666">Message was removed.</i>');
                message.find('a.icon-trash').remove();
            }
            
            function removeMessage(id){
                $.ajax({
                    url: "removeMessage",
                    type: "POST",
                    data: {
                        id: id
                    },
                    success: function(result) {
                        if(result=='true') markAsRemoved(id);
                    }
                });
                $input.focus();
            }
            
            function formatDate(date){
                var dd = date.getDate();
                var MM = date.getMonth();
                var yyyy = date.getFullYear();
                
                var hh = date.getHours();
                var mm = date.getMinutes();
                var ss = date.getSeconds();
                
                return hh+":"+mm+":"+ss+" "+dd+"."+MM+"."+yyyy;
            }
            
            function refresh(){
                updateStatus();
                getPartner();
                if(isActive){
                    if(hasPartner){
                        allowChat(true);
                        $chatinfo.fadeOut(300);
                        getNewMessages();
                        getRemovedMessages();
                    } else {
                        $chatinfo.fadeIn(300);
                        allowChat(false);
                    }
                } else {
                    allowChat(false);
                }
            }
            
            function closeChat(){
                $.ajax({
                    url: "close",
                    type: "POST",
                    success: function() {
                        updateStatus();
                    }
                });
            }
            
            function setVisiblePasswordDialog(isVisible){
                if(isVisible) {
                    $('#passwordDialog').fadeIn(300);
                } else {
                    $('#passwordDialog').fadeOut(300);
                }
            }
            
            function setPassword(){
                var oldpsw = $('#oldPassword').val();
                var newpsw = $('#newPassword').val();
                if(newpsw == $('#confirmPassword').val()){
                    $.ajax({
                        url: "setPassword",
                        type: "POST",
                        data: {
                            oldPassword: oldpsw,
                            newPassword: newpsw
                        },
                        success: function(result) {
                            if(result=='true'){
                                Notifier.success('Password was succesfully changed');
                            } else{
                                Notifier.error('Password was not changed');
                            }
                        }
                    });
                } else {
                    Notifier.error('Passwords do not match');
                }
                setVisiblePasswordDialog(false);
                $('#oldPassword').val('');
                $('#newPassword').val('');
                $('#confirmPassword').val('');
                
            }
        </script>
        
        <title><sitemesh:write property='title'/></title>
        <sitemesh:write property='head'/>
    </head>
    <body onunload="exit()">
        <div class="navbar navbar-fixed-top">
            <div class="navbar-inner">
                <div class="container-fluid">
                    <a style="width: 120px" class="brand">Private Chat</a>
                    <div style="display: inline-block"><span id="chatStatus">Active</span><br/><span id="partner"></span></div>
                    <div class="btn-group pull-right">
                        <c:choose>
                            <c:when test="${isOwner}">
                                <a class="btn dropdown-toggle" data-toggle="dropdown" href="#"><i class="icon-cog"></i>
                                    <span class="caret"></span>
                                </a>
                                <ul class="dropdown-menu">
                                    <li><a title="Set Password" onclick="setVisiblePasswordDialog(true)"><i class="icon-lock"></i> Set password</a></li>
                                    <li><a title="Close Chat" onclick="closeChat()"><i class="icon-download"></i> Close Chat</a></li>
                                    <li><a title="Exit" onclick="exit()"><i class="icon-off"></i> Exit</a></li>
                                </ul>
                            </c:when>
                            <c:otherwise>
                                <a title="Exit" class="btn btn-danger" onclick="exit()"><i class="icon-off"></i></a>
                            </c:otherwise>
                        </c:choose>
                    </div>
                </div>
            </div>
        </div>
        
        <c:choose>
            <c:when test="${availability}">
                <div class="container-fluid">
                    <div class="row-fluid">
                        <div class="span4">
                            <div id="messageContainer" style="height: 450px; width: 100%; border-bottom: 1px #999 dashed; padding-bottom: 10px; margin-bottom: 10px; overflow-x: hidden; overflow-y: hidden;"></div>
                            <div class="form-inline">
                                <span>
                                    <textarea id="text" type="text" style="width: 250px; height: 45px; resize: none" maxlength="300" placeholder="Message"></textarea>
                                </span>
                                <span class="btn-group pull-right">
                                    <a title="Send message" class="btn" id="sendButton" onclick="send()"><i class="icon-pencil"></i></a>
                                    <a title="Refresh" class="btn" onclick="refresh()"><i class="icon-refresh"></i></a>
                                </span>
                            </div>
                            <div id="chatinfo" class="span3 well" style="padding: 60px 20px; position: fixed; top: 0px; right: 0px; width: 100%; height: 100%; z-index: 100; text-align: center; opacity: 0.9">
                                <h1>You are alone!</h1>
                                <p>
                                    Please wait for a partner.<br/>
                                    Your chat ID is: <b>${chatId}</b><br/>
                                    <c:if test="${isOwner}">
                                        <br/>
                                        <a title="Set Password" class="btn" onclick="setVisiblePasswordDialog(true)"><i class="icon-lock"></i> Set password</a>
                                    </c:if>
                                </p>
                                <hr/>
                                <img src='<%=helper.getImageUrl("loading.gif")%>'/>
                                <br/>
                                <hr/>
                                <br/>
                                <br/>
                                <p>You can exit this chat if your partner still do not entered<br/>
                                    Please, click <a title="Exit" class="btn btn-danger" onclick="exit()"><i class="icon-off"></i></a> button to exit.
                                </p>
                            </div>
                            <c:if test="${isOwner}">
                                <div id="passwordDialog" class="span3 well" style="padding: 60px 20px; position: fixed; top: 0px; right: 0px; width: 100%; height: 100%; z-index: 200; text-align: center;">
                                    <h1>Please, set new password</h1>
                                    <div style="text-align: left">
                                    Old password:<br/><input id="oldPassword" type="password" maxlength="20" /><br/>
                                    New password:<br/><input id="newPassword" type="password" maxlength="20" /><br/>
                                    Confirm password:<br/><input id="confirmPassword" type="password" maxlength="20" /><br/>
                                    <a title="Back" class="btn" onclick="setPassword()"><i class="icon-lock"></i> Set Password</a>
                                    <a title="Back" class="btn" onclick="setVisiblePasswordDialog(false)"><i class="icon-arrow-left"></i> Back</a>
                                    </div>
                                    
                                </div>
                            </c:if>

                        </div><!--/span-->
                    </div><!--/row-->
                </div><!--/.fluid-container-->
            </c:when>
            <c:otherwise>
                <div class="container-fluid">
                    <div class="hero-unit">
                        <h1>Sorry!</h1>
                        <p>This chat is not available for you.</p>
                    </div>
                </div><!--/.fluid-container-->
            </c:otherwise>
        </c:choose>
        
        <%=helper.getJs(helper.BOOTSTRAP)%>
    </body>
</html>
